package com.liang.book.interceptor;

import cn.hutool.core.text.AntPathMatcher;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.liang.book.constant.Constant;
import com.liang.book.model.Result;
import com.liang.book.model.Roles;
import com.liang.book.model.UserInfo;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.util.*;
@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor  {
    @Autowired
    private ObjectMapper objectMapper;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,Object handler) throws Exception {
        log.info("检验用户是否登录");
        HttpSession session = request.getSession();
        UserInfo userInfo = (UserInfo) session.getAttribute(Constant.USER_SESSION_KEY);
        if(userInfo == null) {
            //用户未登录
            log.warn("用户未登录");
            response.setStatus(401);
            response.setContentType("application/json;charset=utf-8");
            Result result = Result.fail("用户未登录");
            response.getOutputStream().write(objectMapper.writeValueAsString(result).getBytes());

//            response.getOutputStream().write("nologin".getBytes());
            return false;
        }
        log.info("用户登录成功");


        return true;//false拦截
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("目标方法后执行代码");
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
         log.info("视图渲染完成后执行的代码");
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }





//
//@Component
//@Slf4j
//public class RoleBasedInterceptor implements HandlerInterceptor {
//
//    @Autowired
//    private ObjectMapper objectMapper;
//
//    // 定义角色与可访问路径的映射
//    private static final Map<String, Set<String>> ROLE_PATH_MAP = new HashMap<>();
//    static {
//        ROLE_PATH_MAP.put("user", new HashSet<>(Arrays.asList("/user/**")));
//        ROLE_PATH_MAP.put("admin", new HashSet<>(Arrays.asList("/admin/**", "/user/**")));
//    }
//
//    @Override
//    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        log.info("检验用户角色及可访问路径");
//
//        HttpSession session = request.getSession();
//        UserInfo userInfo = (UserInfo) session.getAttribute(Constant.USER_SESSION_KEY);
//
//        if (userInfo == null) {
//            // 用户未登录
//            log.warn("用户未登录");
//            handleUnauthorized(response, "用户未登录");
//            return false;
//        }
//
//        String userRole = userInfo.getRole();
//        String requestURI = request.getRequestURI();
//
//        // 检查用户角色是否有权访问当前路径
//        if (!hasAccess(userRole, requestURI)) {
//            // 用户角色不允许访问此路径
//            log.warn("用户角色 {} 不允许访问路径 {}", userRole, requestURI);
//
//            // 根据角色重定向到不同的登录页面或错误页面（可选）
//            // 或者直接返回403 Forbidden（下面已经实现了）
//            // response.sendRedirect("/login?role=" + userRole); // 示例重定向
//
//            handleUnauthorized(response, "您没有权限访问此资源");
//            return false;
//        }
//
//        log.info("用户 {} 角色 {} 访问路径 {} 被允许", userInfo.getUserName(), userRole, requestURI);
//        return true; // 允许访问
//    }
//
//    private boolean hasAccess(String role, String requestURI) {
//        Set<String> allowedPaths = ROLE_PATH_MAP.get(role);
//        if (allowedPaths == null) {
//            return false;
//        }
//        for (String path : allowedPaths) {
//            if (AntPathMatcher.match(path, requestURI)) {
//                return true;
//            }
//        }
//        return false;
//    }
//
//    private void handleUnauthorized(HttpServletResponse response, String message) throws IOException {
//        response.setStatus(403); // 403 Forbidden
//        response.setContentType("application/json;charset=utf-8");
//        Result result = Result.fail(message);
//        response.getOutputStream().write(objectMapper.writeValueAsString(result).getBytes());
//    }
//}
//













//        @Override
//        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//            // 获取当前用户（假设你有一个方法来获取当前认证的用户信息）
//            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
//
//            if (authentication != null && authentication.isAuthenticated()) {
//                // 获取用户的角色
//                Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
//
//                // 检查用户是否有访问权限（例如，检查是否有"ROLE_USER"角色）
//                boolean hasAccess = authorities.stream()
//                        .anyMatch(grantedAuth -> grantedAuth.getAuthority().equals("ROLE_USER"));
//
//                if (!hasAccess) {
//                    // 如果没有访问权限，重定向到错误页面或返回403状态码
//                    response.sendError(HttpServletResponse.SC_FORBIDDEN, "Access Denied");
//                    return false;
//                }
//            } else {
//                // 用户未认证，重定向到登录页面（对于非API请求）
//                if (!"application/json".equals(request.getHeader("Accept"))) {
//                    response.sendRedirect("/user/login");
//                } else {
//                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authentication Required");
//                }
//                return false;
//            }
//
//            // 如果有访问权限，继续处理请求
//            return true;
//        }
//    }
}
